package com.mo.lib.utils.time

import android.os.CountDownTimer
import android.widget.TextView
import androidx.annotation.IntRange
import kotlin.math.roundToInt

/**
 * @ author：mo
 * @ data：2018/11/7
 * @ 功能：自定义倒计时,参数限定秒级   secondInFuture=秒级区间 、countDownInterval=间隔时间，默认1秒
 */
/** millisInFuture==从当前时间开始 作用区间 如：5000                countDownInterval ==间隔时间 如：1000  */
open class LCountDownTimer @JvmOverloads constructor(@IntRange(from = 3, to = 60) secondInFuture: Int, @IntRange(from = 1, to = 10) countDownInterval: Int = 1) :
    CountDownTimer(secondInFuture.toLong() * 1000 + 1050, countDownInterval.toLong() * 1000) {
    private var bindView: TextView? = null

    /** 绑定tv文本模板类型：
     * 0==onTicks->"验证码(" + second + ")"、onFinish->获取验证码
     * 1== onTicks-> "$second s后重新获取"、onFinish->"获取验证码"
     * 2== onTicks-> "跳过$second"、onFinish->"跳过" */
    private var type = -1

    /** 倒计时开始  */
    override fun onTick(millisUntilFinished: Long) {
        val second = (millisUntilFinished.toDouble() / 1000).roundToInt() - 1
        if (second <= 0) {
            onFinish()
        } else {
            onTicks(millisUntilFinished, second)
        }
    }

    fun setBindView(textView: TextView, showType: Int = -1): LCountDownTimer {
        bindView = textView
        type = showType
        return this
    }

    /** 倒计时开始 抽象方法       millisUntilFinished ==毫秒数      second ==秒数  */
    open fun onTicks(millisUntilFinished: Long, second: Int) {
        bindView?.let {
            if (it.isEnabled&&type != 2) {
                it.isClickable = false
            }
            if (type == 0) {
                it.text = "验证码($second)"
            } else if (type == 1) {
                it.text = "$second s后重新获取"
            } else if (type == 2) {
                it.text = "跳过$second"
            }
        }
    }

    override fun onFinish() {
        bindView?.let {
            it.isClickable = true
            if (type != -1) {
                if (type == 2) {
                    it.text = "跳过"
                } else {
                    it.text = "获取验证码"
                }
            }
        }
    }
}
